package com.zcs.thread.communication;

/**
 * ThreadLocal为线程本地变量或线程本地存储。
 * 严格来说，ThreadLocal类并不属于多线程间的通信，而是让每个线程有自己”独立“的变量，线程之间互不影响。它为每个线程都创建一个副本，每个线程可以访问自己内部的副本变量。
 * @author zcs
 * @since 2023/4/24
 */
public class ThreadLocalDemo {

    public static void main(String[] args) {
        ThreadLocal<String> threadLocal = new ThreadLocal<>();
        new ThreadA(threadLocal).aVoid();
        new ThreadB(threadLocal).bVoid();
    }


    static class ThreadA {
        private ThreadLocal<String> threadLocal;

        public ThreadA(ThreadLocal<String> threadLocal) {
            this.threadLocal = threadLocal;
        }

        public void aVoid(){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    threadLocal.set("A");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("ThreadA输出：" + threadLocal.get());
                }
            }).start();

        }
    }

    static class ThreadB {
        private ThreadLocal<String> threadLocal;

        public ThreadB(ThreadLocal<String> threadLocal) {
            this.threadLocal = threadLocal;
        }

        public void bVoid(){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    threadLocal.set("B");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("ThreadB输出：" + threadLocal.get());
                }
            }).start();

        }
    }


}
